<script setup>
import { ref } from "vue";
import { add } from "../../api/article";
const formData = ref({
  title: "",
  content: "",
  img: "",
});

const rules = ref({
  title: {
    rules: [{ required: true, errorMessage: "请输入文章标题" }],
  },
  content: {
    rules: [{ required: true, errorMessage: "请输入文章内容" }],
  },
  img: {
    rules: [{ required: true, errorMessage: "请上传文件" }],
  },
});

const handleSelect = (e) => {
  const tempFilePaths = e.tempFilePaths;
  uni.uploadFile({
    fileType: "image",
    filePath: tempFilePaths[0],
    url: "http://localhost:3000/uploads/img",
    name: "file",
    success: ({ data }) => {
      formData.value.img = JSON.parse(data).path;
    },
    fail: (error) => {
      uni.showToast({
        title: "上传失败",
        icon: "fail",
        mask: true,
      });
    },
  });
};

const formRef = ref(null);
const submit = () => {
  formRef.value
    .validate()
    .then(async (res) => {
      const data = await add(formData.value);
      console.log(data);
    })
    .catch((err) => {
      console.log("校验失败", err);
    });
};
</script>

<template>
  <view class="add">
    <uni-forms ref="formRef" :value="formData" :rules="rules" labelWidth="80">
      <uni-forms-item name="title" label="文章标题" required>
        <uni-easyinput v-model="formData.title" placeholder="请输入文章标题" />
      </uni-forms-item>
      <uni-forms-item name="content" label="文章内容" required>
        <uni-easyinput
          type="textarea"
          v-model="formData.content"
          placeholder="请输入文章内容"
        />
      </uni-forms-item>

      <uni-forms-item name="img" label="上传文件" required>
        <uni-file-picker
          :limit="1"
          fileMediatype="image"
          @select="handleSelect"
        />
      </uni-forms-item>
    </uni-forms>
    <view class="add__btn-box">
      <button type="primary" @click="submit">提交</button>
    </view>
  </view>
</template>
